package com.ysw.spring.spring_util.redisson;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import org.redisson.api.RList;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 基于 Redisson 的通用操作工具类
 * <p>
 * Created by zhangqingpo on 2020/08/13.
 */
@Data
//@Component
public class RedissonCommonUtil {

    /** redis前缀，用于区分不同的应用 **/
    @Value("${redis.common.prefix:}")
    public String redisPrefix;

    //@Autowired(required = false)
    @Qualifier("masterRedissonClient")
    private RedissonClient redissonClient;

    public RedissonClient getRedissonClient(){
        return this.redissonClient;
    }
    /**
     * 设值, 并且会重置过期时间
     */
    public void set(String key, Object t, Long timeToLive, TimeUnit timeUnit) {
        redissonClient.getBucket(getRedisKey(key)).set(t, timeToLive, timeUnit);
    }

    /**
     * 取值
     */
    public Object get(String key) {
        return redissonClient.getBucket(getRedisKey(key)).get();
    }

    /**
     * 取值, 并且转换成指定类型
     */
    public <T> T get(String key, Class<T> t) {
        Object o = this.get(key);
        if (null == o) return null;
        return new ObjectMapper().convertValue(o, t);
    }

    /**
     * 设值 list, 并且会重置过期时间
     */
    public void setList(String key, List<?> list, Long timeToLive, TimeUnit timeUnit) {
        RList<Object> redisList = redissonClient.getList(getRedisKey(key));
        redisList.clear();
        redisList.addAll(list);
        redisList.expire(timeToLive, timeUnit);
    }
/*    *//**
     * 取值 list, 并且转换成指定类型
     *//*
    public <T> T getList(String key, TypeReference<?> toValueTypeRef) {
        List<Object> objects = redissonClient.getList(getRedisKey(key)).readAll();
        if (CollectionUtils.isEmpty(objects)){
            return null;
        }
        return new ObjectMapper().convertValue(objects, toValueTypeRef);
    }*/

    /**
     * 自增加一
     */
    public void increment(String key) {
        redissonClient.getAtomicLong(key).incrementAndGet();
    }

    /**
     * 将指定key的value值增加delta
     */
    public void increment(String key, long delta) {
        redissonClient.getAtomicLong(key).addAndGet(delta);
    }

    /**
     * 删除key
     */
    public void remove(String key) {
        redissonClient.getBucket(getRedisKey(key)).delete();
    }

    /**
     * 构建key
     */
    private String getRedisKey(String key) {
        return redisPrefix + ":" + key;
    }

}
